# -*- coding: utf-8 -*-

"""
@author: hsowan <hsowan.me@gmail.com>
@date: 2020/2/10

"""
from gitlab import Gitlab
from github import Github
from gitee import Gitee
from gitea import Gitea
from coding import Coding
import json
import logging
import os
import re
import uuid
from urllib.parse import quote
import requests
import settings
from gitbase import Git

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)


stock_source = dict(
    gitlab=Gitlab,
    github=Github,
    coding=Coding,
    gitea=Gitea,
    gogs=Gitea,
    gitee=Gitee
)

stock_dest = dict(
    gitlab=Gitlab,
    github=Github,
    # coding=Coding, 暂不支持
    gitea=Gitea,
    gogs=Gitea,
    gitee=Gitee
)

def get_source_git():
    source_type = settings.SOURCE_GIT.get('type', '')
    source = stock_source.get(source_type)
    if not source:
        raise ValueError(f'暂不支持此类Git服务器: {source_type}')
    return source(settings.SOURCE_GIT)

def get_dest_git():
    dest_type = settings.DEST_GIT.get('type', '')
    dest = stock_dest.get(dest_type)
    if not dest:
        raise ValueError(f'暂不支持此类Git服务器: {dest_type}')
    return dest(settings.DEST_GIT)

def main():
    from pathlib import Path
    
    Path(settings.TEMP_DIR).mkdir(exist_ok=True, parents=True)    

    source_git = get_source_git()
    dest_git = get_dest_git()

    print(f'fetch repos from {source_git}')
    all_repos = source_git.list_repos()

    for i, repo in enumerate(all_repos):
        print(f'{str(i)}. {repo["name"]}')
    repo_ids = [int(i) for i in input(
        '请输入需要迁移的仓库序号, 以英文逗号分割: ').replace(' ', '').split(',')]
    for repo_id in repo_ids:
        migrate_repo = all_repos[repo_id]
        try:
            repo_dir = source_git.clone_repo(migrate_repo['name'])
            if repo_dir:
                has_create = dest_git.create_repo(**migrate_repo)
                if has_create:
                    dest_git.push_repo(migrate_repo['name'], repo_dir)
        except Exception as e:
            logger.error(e)


if __name__ == "__main__":
    main()
